package sk.vrto.web.presenters;

import com.google.common.eventbus.Subscribe;
import sk.vrto.domain.Email;
import sk.vrto.domain.User;
import sk.vrto.service.dao.EmailRepository;
import sk.vrto.web.base.Presenter;
import sk.vrto.web.events.EmailRemoved;
import sk.vrto.web.views.EmailsView;

import java.util.Collection;

public class EmailsPresenter extends Presenter<EmailsView> {

    private final EmailRepository emailRepository;
    private final User user;

    /**
     * @param emailRepository Repository for accessing emails
     * @param user Logged user
     */
    public EmailsPresenter(EmailRepository emailRepository, User user) {
        this.emailRepository = emailRepository;
        this.user = user;
    }

    /**
     * Removes widget with email, that was removed.
     * @param e Triggering event, contains removed email.
     */
    @Subscribe
    public void onEmailRemoved(EmailRemoved e) {
        view.removeEmailView(e.getView());
        view.refreshVisibleTabs();
        view.updatePageNumber(newPageNumber());
    }

    /**
     * Loads all emails for the user
     * @return Loaded emails
     */
    public Collection<Email> loadEmails() {
        return emailRepository.loadEmailsForUser(user);
    }

    public void nextPage() {
        if (view.getCurrentPage() < view.maxPages() - 1) {
            view.incCurrentPage();
            view.updatePageNumber(newPageNumber());
            view.refreshVisibleTabs();
        }
    }

    public void previousPage() {
        if (view.getCurrentPage() > 0) {
            view.decCurrentPage();
            view.updatePageNumber(newPageNumber());
            view.refreshVisibleTabs();
        }
    }

    /**
     * @return Calculates current page number: current/max
     */
    public String newPageNumber() {
        return view.getCurrentPage() + 1 + " / " + view.maxPages();
    }
}
